using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class StaticManager {
	private static StaticManager instance = null;
	
	public static void DestroyInstance ()
	{
		if (instance == null)
		{
			return;
		}
		
		instance.Destroy();
		instance = null;
	}
	
	public static void InitiateInstance ()
	{
		DestroyInstance();
		instance = new StaticManager();
	}
	
	public static StaticManager Instance
	{
		get
		{
			return instance;
		}
	}

	private Dictionary<string,StaticDataContainer> statics = new Dictionary<string,StaticDataContainer>();
	private Dictionary<string,Dictionary<string,StaticDataContainer>> groups = new Dictionary<string,Dictionary<string,StaticDataContainer>>();
	
	public StaticManager ()
	{
		
	}
	
	public void Destroy ()
	{
		
	}
	
	public StaticDataContainer GetStatic (string staticId)
	{
		if (statics.ContainsKey(staticId))
		{
			StaticDataContainer staticData = statics[staticId];
			return staticData;
		}
		return null;
	}
	
	public bool AddStatic (StaticDataContainer staticData)
	{
		if (staticData == null)
		{
			Debug.LogError("Cannot add a null staticData.");
			return false;
		}

		if (statics.ContainsKey(staticData.StaticId))
		{
			return false;
		}

		if (!staticData.ReadOnly)
		{
			staticData.ReadOnly = true;
		}

		statics.Add(staticData.StaticId , staticData);
		AddStaticToGroups(staticData);
		return true;
	}

	public bool RemoveStatic (string staticId)
	{
		if (!statics.ContainsKey(staticId))
		{
			return false;
		}

		StaticDataContainer staticData = statics[staticId];
		RemoveStaticFromGroups(staticData);
		statics.Remove(staticId);
		return true;
	}

	private void AddStaticToGroups (StaticDataContainer staticData)
	{
		string[] groupIds = staticData.CopyGroupIds();
		for (int i = 0 ; i < groupIds.Length ; i++)
		{
			string groupId = groupIds[i];

			Dictionary<string,StaticDataContainer> group;
			if (!groups.ContainsKey(groupId))
			{
				group = new Dictionary<string,StaticDataContainer>();
				groups.Add(groupId , group);
			}
			else
			{
				group = groups[groupId];
			}

			if (group.ContainsKey(staticData.StaticId))
			{
				continue;
			}

			group.Add(staticData.StaticId , staticData);
		}
	}

	private void RemoveStaticFromGroups (StaticDataContainer staticData)
	{
		string[] groupIds = staticData.CopyGroupIds();
		for (int i = 0 ; i < groupIds.Length ; i++)
		{
			string groupId = groupIds[i];

			if (!groups.ContainsKey(groupId))
			{
				continue;
			}

			Dictionary<string,StaticDataContainer> group = groups[groupId];
			
			if (!group.ContainsKey(staticData.StaticId))
			{
				continue;
			}
			
			group.Remove(staticData.StaticId);
		}
	}
}
